package com.yyaccp.appinfo.controller;

import com.yyaccp.appinfo.domain.DevUser;
import com.yyaccp.appinfo.exception.LoginException;
import com.yyaccp.appinfo.service.DevUserService;
import com.yyaccp.appinfo.utils.AjaxResult;
import com.yyaccp.appinfo.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpSession;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/devUsers")
public class DevUserController {

    @Autowired
    private DevUserService devUserService;

    @PostMapping("/login")
    public AjaxResult login(DevUser user, HttpSession session){
        try {
            DevUser devUser = devUserService.login(user);
            devUser.setDevPassword("******");
            session.setAttribute(Constants.LOGIN_USER,devUser);
            return AjaxResult.success(devUser);
        }catch (LoginException ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @GetMapping("/getLoginUser")
    public AjaxResult getLoginUser(HttpSession session){
        DevUser user = (DevUser) session.getAttribute(Constants.LOGIN_USER);
        if (user == null) {
            return AjaxResult.error();
        }
        return AjaxResult.success(user);
    }
}
